<template>
    <div class="hall-container">
        <Music ref="musicRef" />
        <!-- <audio :src="audioSrc" ref="audioRef" loop autoplay></audio> -->
        <div class="user-info">
            <div class="user-name">
                <span>用户名：</span>
                <span>{{ user.username }}</span>
            </div>
            <div class="user-account">
                <span>账号：</span>
                <span>{{ user.account }}</span>
            </div>
            <div class="user-chip">
                <span>筹码：</span>
                <span>{{ user.chip }}</span>
            </div>
            <div class="user-level">
                <span>等级：</span>
                <span>{{ user.level }}</span>
            </div>
        </div>

        <div class="center-buttons">
            <img src="@/assets/images/hall_user.png" alt="" class="decoration-left">
            <div class="buttons-group">
                <img src="@/assets/images/button/create_room.png" alt="创建房间" @click="createRoom" class="action-button">
                <img src="@/assets/images/button/match_room.png" alt="快速匹配" @click="quickMatch" class="action-button">
                <img src="@/assets/images/button/enter_room.png" alt="加入房间" @click="joinRoom" class="action-button">
            </div>
            <img src="@/assets/images/hall_user2.png" alt="" class="decoration-right">
        </div>

        <div v-if="matching" class="matching-overlay">
            <img src="@/assets/images/match.png" alt="正在匹配" class="matching-image">
        </div>
        <el-dialog v-model="matchVisible" title="选择游戏类型" width="30%">
            <div class="type-select">
                <div class="select-item">
                    <span>桌子：</span>
                    <el-select v-model="selectedTableType" placeholder="请选择桌子类型">
                        <el-option v-for="item in tableTypes" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>
                <div class="select-item">
                    <span>游戏：</span>
                    <el-select v-model="selectedGameType" placeholder="请选择游戏类型">
                        <el-option v-for="item in gameTypes" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>
            </div>
            <span slot="footer">
                <el-button @click="matchVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmMatch">确认匹配</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue';
import http from '@/utils/http';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import Music from '@/components/Music.vue'
import { useStore } from 'vuex'
const store = useStore()
const musicRef = ref(null)
const router = useRouter();
const user = ref({
    username: '',
    account: '',
    chip: 0,
    level: 0,
    id: null
});
const matching = ref(false);
const audioRef = ref(null);
const eventSource = ref(null);

const matchVisible = ref(false);
const selectedTableType = ref('');
const selectedGameType = ref('');
// 修改后的 quickMatch 方法，增加了 console.log 用于调试

const gameTypes = [
    { label: '斗地主', value: '1' },
];
const tableTypes = [
    { label: '娱乐场', value: '1', minChips: 0 },
    { label: '初级场(0-1000筹码)', value: '2', minChips: 0 },
    { label: '中级场(1000-50000筹码)', value: '3', minChips: 1000 },
    { label: '高级场(50000以上筹码)', value: '4', minChips: 50000 }
];

onMounted(() => {
    // 确保子组件已挂载后再调用 playbg 方法
    if (musicRef.value && musicRef.value.playbg) {
        musicRef.value.playbg('bg_room0', true)
    }
    getUserInfo();
});

onBeforeUnmount(() => {
    if (audioRef.value) {
        audioRef.value.pause();
        audioRef.value.currentTime = 0;
    }
    if (eventSource.value) {
        eventSource.value.close();
    }
});

const getUserInfo = async () => {
    try {
        const res = await http.get('/user/get');
        if (res.code === 100) {
            user.value = res.data;
            store.dispatch('user/setUserInfo', res.data);
        } else {
            ElMessage.error(res.msg);
        }
    } catch (error) {
        ElMessage.error('获取用户信息失败');
        console.error('获取用户信息失败:', error);
    }
};

const quickMatch = () => {
    console.log('快速匹配按钮被点击');
    matchVisible.value = true;
    console.log('matchVisible:', matchVisible.value); // 确认值是否已更新
};

const confirmMatch = async () => {
    if (!selectedGameType.value || !selectedTableType.value) {
        ElMessage.error('请选择游戏类型和桌子类型');
        return;
    }
    matchVisible.value = false;
    matching.value = true;
    try {
        const res = await http.get(`/match/join?game=${selectedGameType.value}&table=${selectedTableType.value}&id=${user.value.id}`);
        if (res.code === 100) {
            ElMessage.success('已加入匹配队列');
            startMatchPolling();
        } else {
            ElMessage.error(res.msg);
            matching.value = false;
        }
    } catch (error) {
        ElMessage.error('加入匹配队列失败');
        matching.value = false;
    }
};
// 确保只有一个createRoom函数定义
const createRoom = () => {
    ElMessageBox.prompt('请输入房间密码(0-6位数字)', '创建房间', {
        inputType: 'password',
        inputPattern: /^\d{0,6}$/,
        inputErrorMessage: '密码必须为0-6位数字',
        confirmButtonText: '创建',
        cancelButtonText: '取消'
    }).then(({ value }) => {
        // TODO: 调用创建房间接口
        ElMessage.success(`房间创建成功，密码: ${value}`);
    }).catch(() => {
        ElMessage.info('取消创建房间');
    });
};

// 确保音乐自动播放
onMounted(() => {
    if (musicRef.value) {
        musicRef.value.playbg('bg_room0', true);
    }
    getUserInfo();
});

const joinRoom = () => {
    ElMessageBox.prompt('请输入房间编号', '加入房间', {
        inputPattern: /^\d+$/,
        inputErrorMessage: '房间编号必须为数字',
        confirmButtonText: '下一步',
        cancelButtonText: '取消'
    }).then(({ value: roomId }) => {
        ElMessageBox.prompt('请输入房间密码', '加入房间', {
            inputType: 'password',
            inputPattern: /^\d{0,6}$/,
            inputErrorMessage: '密码必须为0-6位数字',
            confirmButtonText: '加入',
            cancelButtonText: '取消'
        }).then(({ value: password }) => {
            // TODO: 调用加入房间接口
            ElMessage.success(`正在加入房间 ${roomId}`);
        }).catch(() => {
            ElMessage.info('取消加入房间');
        });
    }).catch(() => {
        ElMessage.info('取消加入房间');
    });
};
const startMatchPolling = () => {
    console.log('开始匹配轮询');    // 确认值是否已更新
    if (eventSource.value) {
        eventSource.value.close();
    }

    eventSource.value = new EventSource(`${process.env.VUE_APP_BASE_SSE}/api/match/send?id=${user.value.id}`, { withCredentials: true });

    eventSource.value.addEventListener('message', (event) => {
        try {
            const data = JSON.parse(event.data);
            console.log('解析后的数据:', data);
            if (data.status === 1) {
                store.dispatch('user/setRoomInfo', data);
                matching.value = false;
                ElMessage.success('匹配成功！即将进入房间...');
                eventSource.value.close();
                router.push('/room');
            }
        } catch (e) {
            //console.error('JSON 解析失败:', e);
        }
    });

    eventSource.value.addEventListener('error', (err) => {
        console.error('SSE 错误:', err);
        // 根据需求决定是否关闭连接或重试等
    });
};

// const startMatchPolling = () => {
//     console.log('开始匹配轮询');    // 确认值是否已更新
//     if (eventSource.value) {
//         eventSource.value.close();
//     }
//     //eventSource.value = new EventSource(process.env.VUE_APP_BASE_SSE + process.env.VUE_APP_BASE_API + `/match/send?id=${user.value.id}`);
//     eventSource.value = new EventSource(process.env.VUE_APP_BASE_SSE + process.env.VUE_APP_BASE_API + `/match/send?id=${user.value.id}`, { withCredentials: true });

//     eventSource.value.addEventListener('message', (event) => {
//         console.log('收到消息:', event.data);
//         try {
//             const data = JSON.parse(event.data);
//             if (data.code === 100 && data.data === 'matched') {
//                 matching.value = false;
//                 ElMessage.success('匹配成功！即将进入房间...');
//                 eventSource.value.close();
//                 router.push('/room');
//             }
//         } catch (e) {
//             console.error('JSON 解析失败:', e);
//         }
//     });

//     eventSource.value.onerror = (err) => {
//         console.error('SSE 错误:', err);
//     };
//     eventSource.value.onmessage = (event) => {
//         console.log('Received SSE message:', event);
//         const data = JSON.parse(event.data);
//         if (data.code === 100 && data.data === 'matched') {
//             matching.value = false;
//             ElMessage.success('匹配成功！即将进入房间...');
//             eventSource.value.close();
//             router.push('/room'); // 匹配成功后跳转到room页面
//         } else if (data.code !== 100) {
//             ElMessage.error(`匹配失败: ${data.msg}`);
//             matching.value = false;
//             eventSource.value.close();
//         }
//     };

//     eventSource.value.onerror = (error) => {
//         console.error('SSE Error:', error);
//         // ElMessage.error('匹配连接异常');
//         // matching.value = false;
//         // eventSource.value.close();
//     };
// };
</script>

<style lang="scss" scoped>
.hall-container {
    position: relative;
    width: 100vw;
    height: 100vh;
    background-image: url('@/assets/images/bg_hall.png');
    background-size: cover;
    background-position: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.user-info {
    position: absolute;
    top: 20px;
    left: 20px;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    padding: 15px;
    border-radius: 10px;
    font-size: 1.1em;
    z-index: 10;

    div {
        margin-bottom: 5px;

        &:last-child {
            margin-bottom: 0;
        }
    }

    span:first-child {
        font-weight: bold;
        margin-right: 5px;
    }
}

.center-buttons {
    display: flex;
    align-items: center;
    gap: 50px;
    /* 按钮组和装饰图片之间的间距 */
    z-index: 5;
}

.buttons-group {
    display: flex;
    flex-direction: column;
    gap: 20px;
    /* 按钮之间的间距 */
}

.action-button {
    width: 250px;
    /* 按钮图片宽度 */
    height: auto;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:hover {
        transform: scale(1.05);
    }
}

.decoration-left,
.decoration-right {
    width: 200px;
    /* 装饰图片宽度 */
    height: auto;
}

.matching-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.matching-image {
    width: 300px;
    /* 匹配图片大小 */
    height: auto;
}

.type-select {
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-bottom: 10px;
}

.select-item {
    display: flex;
    align-items: center;
    gap: 10px;
}
</style>